import { useState,useRef } from "react";

const useWebsocket = (url: string) => {
  // 连接服务器
  const socket = useRef(new WebSocket(url));
  //   定义变量接收新消息
  const [message, setMessage] = useState("");
  //  接收消息
  socket.current.onmessage = (e) => {
    setMessage(e.data);
    console.log('====================================');
    console.log(e);
    console.log('====================================');
  };
  // 发消息
  const sendMessage = (msg: string) => {
    socket.current.send(msg);
  };
  // 断网重连
  // 监听websocket关闭连接的事件
  socket.current.onclose = () => {
    // 重连
    socket.current = new WebSocket(url);
  };

  // 返回
  return { message, sendMessage };
};

export default useWebsocket;
